import {AfterViewInit, Component, OnDestroy, OnInit, ViewEncapsulation} from '@angular/core';
import {AbstractControl, FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute, Params, Router} from '@angular/router';
import {EventsService} from '@core/events/events.service';
import {ToolbarService} from '@shared/components/toolbar/toolbar.service';
import {AuthService} from '@shared/service/auth/auth.service';
import {ToolsService} from '@shared/service/tools/tools.service';
import {UserActivityService} from '@shared/service/user-activity/user-activity.service';
import {ValidationService} from '@shared/service/validator/validator.service';
import {Subscription} from 'rxjs';
import {RedirectionService} from "@redirection/redirection.service";

/**
 * @description 姚明篮球训练组织id
 * 测试环境组织id  seedp543381 account: 15815587063 psw:123456
 * 正式环境组织id  seedp34642
 * @type {string}
 */
const YAO_TRAIN_AUTHORG_ID = 'seedp34642'; // 测试环境id  seedp543381 预发布环境id seedp231 // 正式环境 seedp34642

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class LoginComponent implements OnInit, OnDestroy, AfterViewInit {
  public loginForm: FormGroup;
  public account: AbstractControl;
  public password: AbstractControl;
  public phoneError = '';
  public pswError = '';
  public invalidPhoneNumber = false;
  public passwordLimitLength = false;
  public entrying = false;
  public accountEntrying = true;
  public pswEntrying = false;
  public error = {
    validateCode: false
  };
  public stateStore = {
    showValidateCode: false,  //  显示验证码
  };
  public dataStore = {
    imgValidateCode: '',  //  图片验证码
    randomKey: '',  //  图片验证码随机码
  };
  public showThirdLogin = true;
  public timerCount = 0; // 已设置的数量
  public timerTime = 0;  // 轮训的次数
  protected authOrgId: string; // 姚篮球培训组织id

  subscription: Subscription = new Subscription();

  constructor(
    public router: Router,
    public formBuilder: FormBuilder,
    public tools: ToolsService,
    public userData: AuthService,
    public user: UserActivityService,
    public toolBarService: ToolbarService,
    public events: EventsService,
    private _redirectionService: RedirectionService,
    private _route: ActivatedRoute
  ) {
    this.loginForm = this.formBuilder.group({
      'account': ['', [Validators.required, Validators.minLength(6), Validators.maxLength(50)]],
      'loginPwd': ['', [Validators.required, Validators.minLength(6), Validators.maxLength(16)]],
      //  'validateCode': ['', [Validators.required,Validators.minLength(4), Validators.maxLength(4)]]
    });
    this.events.publish('progressbar:hide');
    this._route.queryParams
      .subscribe((params: Params) => {
        params['authOrgId'] === YAO_TRAIN_AUTHORG_ID && (this.authOrgId = params['authOrgId'], this.showThirdLogin = false);
      });
  }


  ngOnInit() {
    // console.log(this.userData.redirectUrl)
    this.subscription.add(
      this.loginForm.valueChanges
        .debounceTime(300)   //  开始输入之后500毫秒内只取最新的结果
        .subscribe(form => {
          if (this.loginForm.controls['account'].errors) {   //  判断账号框是否有错
            this.invalidPhoneNumber = true;
            this.phoneError = ValidationService.getValidatorErrorMessage('accountlength');
          } else {
            this.invalidPhoneNumber = false;   //  否则就不显示错误提示
          }
          if (!this.loginForm.controls['loginPwd'].pristine && !this.loginForm.controls['loginPwd'].hasError('required')) {
            // 判断密码框是否输入过和非空
            if (this.loginForm.controls['loginPwd'].errors) {   //  如果密码框有错误
              this.passwordLimitLength = this.loginForm.controls['loginPwd'].errors['passwordLimitLength'];   //  去验证结果
              this.pswError = ValidationService.getValidatorErrorMessage('passwordLimitLength');
            } else {
              this.passwordLimitLength = false;   //  否则不显示错误提示
            }
          }
        })
    );
  }

  login() {
    this.tools.showLoading();
    let data = this.loginForm.value;
    let randomKey: string = this.dataStore.randomKey;
    data.loginPwd = this.tools.encryption(data.loginPwd);  //  密码加密
    //  出现图片验证码
    if (randomKey) {
      data['randomKey'] = randomKey;
    }
    this.subscription.add(
      this.user.login(data).subscribe((res) => {
        this.tools.hideLoading();
        if (res.result === '0' && res.data) {
          this.handleLoginSuccess(res.data);
        } else if (res.result === '13') {
          this.tools.showToast('用户不存在', 800);
        } else if (res.result === '11') {  //  用户名或密码错误
          if (res.data === 3) {  //  错误3次
            this.showValidateCode();
          } else if (res.data < 3) {
            this.tools.showToast('用户名或密码输入错误', 800);
          } else {
            this.showValidateCode();
            this.tools.showToast('用户名或密码输入错误', 800);
          }
        } else if (res.result === '6') {  //  输入密码次数超过3次
          this.showValidateCode();
          this.tools.showToast('验证码输入错误', 800);
        } else if (res.result === '46') {  //  输入密码次数超过10次
          this.tools.showToast('密码输错次数超过限制', 800);
        } else {
          this.tools.showToast('登录出错请刷新后重试', 800);
        }
      })
    );
  }

  /**
   * @description 登录成功操作
   * @author ouyqx-691
   * @date 2017-09-19
   * @param result 登录成功后返回的数据
   */
  handleLoginSuccess(result) {
    let redirectURL = this.userData.redirectUrl;
    // console.log(redirectURL)
    if (!redirectURL || redirectURL === '/auth/login') {
      redirectURL = '/';  //  重定向到首页
    }
    this.userData.login(result.userId, result.token, result.refreshToken);
    this.tools.hideLoading();
    this.router.navigateByUrl(redirectURL);
  }

  /**
   * @description 处理验证码（密码输入次数超过3次显示验证码）
   * @author ouyqx-691
   * @date 2017-09-19
   */
  showValidateCode(stateCode?: number) {
    this.getImgValidateCode();
    if (!this.stateStore.showValidateCode) {
      this.stateStore.showValidateCode = true;   // 显示验证码
      this.tools.showToast('请先输入验证码', 800);
    }
    this.loginForm.addControl('validateCode', new FormControl('', [Validators.required, Validators.minLength(4), Validators.maxLength(4)]));
  }

  /**
   * @description 获取图片验证码
   * @author ouyqx-691
   * @date 2017-09-19
   * @param params{type:类型,width:宽度,height:高度}
   */
  getImgValidateCode() {
    const params = {
      type: 1,
      width: 100,
      height: 45
    };
    this.user.getImgValidateCode(params).subscribe(res => {
      if (res.result === '0') {
        this.dataStore.imgValidateCode = res.data.image;
        this.dataStore.randomKey = res.data.key;
      }
    });
  }


  /**
   * @description 发起第三方登陆
   * type == 1 => qq登陆
   * type == 2 => 微博登陆
   * type == 3 => 微信公众号登陆（作废用下面的doWechatLogin）
   * @author @chenwh576
   * @date 2017-11-21
   * @param {number} type
   */
  doThirdLogin(thirdType: number) {
    const host = window.location.host;
    this.user.callThirdLogin(thirdType, host)
      .subscribe(res => {
        if (res.result === "0" && res.data) {
          const location = '/';
          this._redirectionService.setRedirectUrl(location, res.data.authorizeUrl);
        }
      });
  }

  doWechatLogin() {
    this.user.callWechatLogin().subscribe(res => {
      if (res['result'] === "0" && res['data']) {
        const location = '/';
        this._redirectionService.setRedirectUrl(location, res.data.authorizeUrl);
      }
    });
  }

  ngAfterViewInit() {
    if (this.tools.ua().isWeixin) {
      const timer = setInterval(() => {
        const telVal = (<HTMLInputElement>document.getElementById('login-account')).value;
        const pswVal = (<HTMLInputElement>document.getElementById('login-password')).value;
        if (telVal) {
          this.loginForm.controls['account'].setValue(telVal);
          this.timerCount++;
        }
        if (pswVal) {
          this.loginForm.controls['loginPwd'].setValue(pswVal);
          this.timerCount++;
        }
        if (this.timerCount >= 2) {
          clearInterval(timer);
        }
      }, 300);
    }
  }
  ngOnDestroy() {
    // 取消订阅
    this.subscription.unsubscribe();
    this.tools.hideLoading();
  }
}
